/**
 * @file codeforces/1696/c/main.cpp
 * @brief
 * @see
 * @author Ruiming Guo (guoruiming@stu.scu.edu.cn)
 * @copyright 2022
 * @date 2022/6/26 20:55:46
 **/

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
int main() {
  // High rating and good luck!
  int tc;
  cin >> tc;
  while (tc--) {
    ll n, m;
    cin >> n >> m;
    vector<vector<pair<ll, ll>>> res;
    for (int i = 0; i < 2; ++i) {
      ll k;
      if (i == 0)
        k = n;
      else
        cin >> k;
      vector<ll> a(k);
      for (ll &r : a) cin >> r;
      vector<pair<ll, ll>> freq;
      for (ll x : a) {
        ll cnt = 1;
        while (x % m == 0) {
          x /= m;
          cnt *= m;
        }
        if (freq.empty() || freq.back().first != x) {
          freq.emplace_back(x, cnt);
        } else {
          freq.back().second += cnt;
        }
      }
      res.push_back(freq);
    }
    cout << (res[0] == res[1] ? "Yes\n" : "No\n");
  }
  return 0;
}
